package ar.edu.unq.leezsi.utils;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletResponse;

import ar.edu.unq.leezsi.exception.CowebRuntimeException;

public class ResponseWriter {

	private PrintWriter writer;
	private final HttpServletResponse response;

	public ResponseWriter(HttpServletResponse res) {
		this.response = res;
		try {
			this.writer = res.getWriter();
		} catch (IOException e) {
			throw new CowebRuntimeException(e);
		}
	}

	public HttpServletResponse getResponse() {
		return this.response;
	}

	public PrintWriter getWriter() {
		return this.writer;
	}

	public ResponseWriter setMime(String mime) {
		this.response.setContentType(mime);
		return this;
	}

	public void write(InputStream resource) {
		byte[] buffer;
		try {
			buffer = new byte[resource.available()];
			resource.read(buffer);
			this.writer.write(new String(buffer));
		} catch (IOException e) {
			throw new CowebRuntimeException(
					"Error writing resource in response", e);
		}
	}

	public ResponseWriter write(String text) {
		this.writer.write(text);
		return this;
	}

	public void writeException(Exception e) {
		String template = ClassUtils.wrapperFor(this).getResourceAsString(
				"ErrorPageTemplate.html");
		template = template.replace("$errorMsg$", e.toString());

		StringBuilder stack = new StringBuilder();
		StackTraceElement[] stackTrace = e.getStackTrace();
		for (StackTraceElement stackTraceElement : stackTrace) {
			stack.append("<ul>")//
					.append("at " + stackTraceElement.getClassName())//
					.append("." + stackTraceElement.getMethodName())//
					.append("(" + stackTraceElement.getFileName())//
					.append(":" + stackTraceElement.getLineNumber() + ")")//
					.append("</ul>");
		}
		template = template.replace("$stackTrace$", stack);
		this.writer.write(template);
		this.writer.flush();

	}
}
